<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    /*width: 44%;*/
    display: inline-block;
    /*padding: 5px 3%;*/
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    /*width: 50%;*/
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .list {
    background: #eee;
    padding-bottom: 160px;
    overflow: auto;
  }
  .weui-form-preview {
    background-color: #fff;
    margin: 5px;
    border-radius: 5px;
  }
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .list .rj-cell {
    display: inline-block;
    font-size: 0;
    padding: 5px 15px;
    width: 100%;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
  }
  .rj-cell span {
    padding-left: 5px;
    font-size: 14px;
    color: #333;
  }
  .weui-cells {
    border-radius: 5px;
    margin-top: 0;
  }
  .paylayer {
    width: 100%;
    text-align: center;
    position: fixed;
    bottom: 0;
    border-top: 1px solid #ddd;
    background: #fff;
    z-index: 100;
  }
  .rj-cell span i {
    color: red;
    font-size: 30px;
    font-style: normal;
  }
  .paylayer .rj-cell {
    padding: 5px;
    display: inline;
  }
  .all-btn {
    position: absolute;
    right: 0;
    top: 0;
    width: 130px;
    text-align: right;
  }
  .all-btn i {
    font-size: 16px;
    position: absolute;
    left: -7px;
    top: 8px;
  }
  .weui-cells {
    text-align: left;
  }
</style>
<template>
  <div class="comon">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      回款登记
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input type="hidden" name="entity.currency" :value="customer.currency" />
        <div class="weui-cell weui-cell_select" style="padding: 0 15px;">
          <div class="weui-cell__hd"><label class="weui-label">部门：</label></div>
          <div class="weui-cell__bd">
            <input type="hidden" name="entity.departname" :value="depart.name" />
            <input type="hidden" name="entity.departid" :value="depart.guid" />
            <select class="weui-select" v-model="depart">
              <option value="">请选择部门</option>
              <option selected=""  v-for="(item, index) in departments" :key="item.guid" :value="item">{{item.name}}</option>
            </select>
          </div>
        </div>
        <div class="weui-cell weui-cell_select" style="padding: 0 15px;">
          <div class="weui-cell__hd"><label for="" class="weui-label">客户</label></div>
          <div class="weui-cell__bd">
            <select class="weui-select" id="customer" name="entity.customerid" v-model="customerid">
              <option value="" style="color: #ccc;">请选择客户</option>
              <option  v-for="(item, i) in customers" :value="item.guid" >{{item.name}}</option>
            </select>
          </div>
        </div>
        <div class="weui-cell" v-if="customer != ''">
          <div class="weui-cell__hd"><label class="weui-label">应收账款({{customer.currency == 2 ? '美元' : '元'}})</label></div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="number" readonly :value="customer.recbalance">
          </div>
        </div>
        <div class="weui-cell" v-if="customer != ''">
          <div class="weui-cell__hd"><label class="weui-label">预收款余额({{customer.currency == 2 ? '美元' : '元'}})</label></div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="number" readonly :value="customer.prebalance">
          </div>
        </div>
<!--        <div class="weui-cell">-->
<!--          <div class="weui-cell__hd"><label class="weui-label">回款金额(元)</label></div>-->
<!--          <div class="weui-cell__bd">-->
<!--            <input class="weui-input" type="number" name="entity.prepaid">-->
<!--          </div>-->
<!--        </div>-->
        <div class="weui-cell">
          <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
          <div class="weui-cell__bd">
            <textarea class="weui-textarea" name="entity.remark" placeholder="请输备注内容" rows="3"></textarea>
          </div>
        </div>
        <div class="weui_cell" style="position: relative;">
          <div class="weui_cell_bd weui_cell_primary">
            <div class="weui_uploader">
              <div class="rj-cell all-btn" style="" >
                <!--          <div class="rj-cell all-btn" style="" id="allSec">-->
                <!--            <i class="weui-icon-circle"></i>-->
                <!--            <label>全选</label>-->
                <label @click="addOrder" style="color: #0bb20c;padding: 10px 15px;">添加订单</label>
              </div>
              <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                <div class="weui_cell_bd weui_cell_primary" id="outstore">附件上传</div>
                <div class="weui_cell_ft" id=""></div>
              </div>
              <div class="weui_uploader_bd">
                <ul class="weui-uploader_files" id="images">
                  <li class="weui-uploader_file" v-for="(img, index) in images.serverId" :id="img"  @click=del(img,1) ><img :src="images.srcStr[index]" width="85" /></li>
                </ul>
                <div class="weui_uploader_input_wrp">
                  <input type="button" id="selectImage"  class="weui_uploader_input" >
                </div>
              </div>
            </div>
          </div>
        </div>
<!--        <div class="weui-btn-area">-->
<!--          <a class="weui-btn weui-btn_primary subbtn" href="javascript:" @click="postForm">提交</a>-->
<!--        </div>-->
      </form>
    </div>
    <div class="list" id="list">
      <div class="weui-form-preview" v-for="(item, index) in orders" :key="item.guid">
        <div class="weui-cells weui-cells_checkbox">
          <div class="weui-cell">
            <div class="weui-cell__bd weui-cell_primary payitem" data-guid="">
              <p> </p>
              <div class="rj-cell max">
                <label>销售单号：</label>
                <span>{{item.ordercode}}</span>
              </div>
              <div class="rj-cell max">
                <label>结算金额({{item.currency == 2 ? '美元' : '元'}})：</label>
                <span>{{item.amount}}</span>
              </div>
              <div class="rj-cell max">
                <label>备注：</label>
                <span>{{item.remark}}</span>
              </div>
              <p></p>
            </div>
<!--            <label class="weui-check_label weui-cell__ft" :for="'weui-select-id-' + item.orderid">-->
<!--              <input type="checkbox" class="weui-check" name="weui-select" :value="item.orderid" :data-amount="item.amount" :data-guid="item.orderid" :id="'weui-select-id-' + item.orderid" />-->
<!--              <span class="weui-icon-checked"></span>-->
<!--            </label>-->
          </div>
        </div>
      </div>
    </div>
    <div class="paylayer">
      <div class="rj-cell">
        <label>合计：</label>
      </div>
      <div class="rj-cell">
        <label></label>
        <span id="carnum"><i>0</i> 单</span>
      </div>
      <!--      <div class="rj-cell">-->
      <!--        <label></label>-->
      <!--        <span id="weight"><i>0</i> 吨</span>-->
      <!--      </div>-->
      <div class="rj-cell">
        <label></label>
        <span id="amount"><i>0</i> {{customer.currency == 2 ? '美元' : '元'}}</span>
      </div>
<!--      <div class="weui-cell" style="display: block">-->
<!--        <div class="weui-cell__bd">-->
<!--          <textarea class="weui-textarea" name="" v-model="opinion" placeholder="请输入审批意见" rows="2"></textarea>-->
<!--        </div>-->
<!--      </div>-->
      <div class="weui-form-preview__ft">
        <a class="weui-form-preview__btn weui-form-preview__btn_primary subbtn" @click="postForm" href="javascript:">确定</a>
        <a class="weui-form-preview__btn weui-form-preview__btn_default" @click="$router.back(-1)">返回</a>
      </div>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';

export default {
  name: 'AddPayback',
  data () {
    return {
      id: '',
      customers: [],
      customer: '',
      customerid: '',
      wxParams: {},
      images: {
        serverId: [],
        srcStr: [],
      },

      fromOrderlist: false,
      payback: {},
      orders: [],
      totalAmoumt: 0,
      totalGuids: '',
      selected : false,
      opinion: '',
      nodeid: '',
      annex: '',
      departments: [],
      depart: "",

    }
  },
  mounted () {
    let that = this;
    this.fromOrderlist = this.$route.query.reffer ? true : false;

    if (this.fromOrderlist) {
      this.customerid = this.$route.query.customerid;
    }

    this.getCustomers();
    this.getUpImagInfo(this);
    this.getDepartment();
    //this.orders = this.orders.concat(this.$store.state.sellforms);

    //首次加载为未选中状态
    $('#allSec').click(function(){
      var elem = $('input[name="weui-select"]');
      for (var i=0; i< elem.length; i++) {
        if (!elem.eq(i).is(':checked')) {
          that.selected = true;
        }
      }
      if (that.selected) {
        that.switchChecked(false, elem);
      } else {
        that.switchChecked(true, elem);
      }
    })


    //图片浏览器
    $('#app').on('click', '.uploaderFiles .attachimg', function () {
      var num = $(this).parent().children().not( ".exp" ).length;
      var imgArr = [];
      for (var i=0; i<num; i++) {
        imgArr.push($(this).parent().find('.attachimg').eq(i).data('img'));
      }
      var pnum = $(this).parent().find('.exp').length;
      var index = pnum > 0 ? $(this).index() - pnum : $(this).index();
      var pb = $.photoBrowser({
        items: imgArr,
        initIndex: index
      });
      console.log('imgArr:', imgArr)
      pb.open();
    });
  },
  watch: {
    'customerid': function (val) {
      if (this.customers.length > 0) {
        this.customer = val != '' ? this.customers.filter(function (item) {
          return item.guid == val;
        })[0] || '' :  '';
      }
      //添加订单返回赋值给本组件
      this.orders = this.$route.query.customerid == val ? this.$store.state.sellforms : [];

      //选择运单后计算总支付金额
      this.getFinalAmount();

    }
  },
  methods: {
    getDepartment: function() {
      let that = this;
      this.axios({
        method: 'get',
        responseType: 'json',
        url: '/sales/Sellform!findDepartment.action',
        params: {sPermission: 2}
      }).then(response => {
        if (response.data.status == "true") {
          //that.departments = response.data.result.map(that.filterDepartment);
          that.departments = response.data.result;
          that.depart = response.data.result.length > 0 ? response.data.result[0] : '';
        } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastText('获取部门数据失败');
        }
      });
    },
    wxConfig: function(wxParams) {
      wx.config({
        debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: wxParams.appid,    // 必填，公众号的唯一标识
        timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
        nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
        signature: wxParams.signature,// 必填，签名
        jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
      });
    },
    wxUoloadImage: function(that) {
      let cthis = this;
      //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images.srcStr.push(n);
                        })
                      }

                      cthis.images.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
    },
    checkCore:function() {
      var u = navigator.userAgent;
      //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
      if (isIOS) {
        return 'ios';
      } else  {
        return 'android';
      }
    },
    getWxSignLink: function() {
      // 记录进入 App 时的 URL
      if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
        window.entryUrl = location.href;
      }

      return /(Android)/i.test(navigator.userAgent) ? location.href : window.entryUrl;
    },
    getUpImagInfo: function(that) {
      this.axios({
        method: 'post',
        url: '/pay/Paybackinfo!getUpImagInfo.action',
        params: {url: location.href.split("#")[0]}
      }).then(response => {
        if (response.status == 200) {
            let wxParams = response.data.params;
          //配置微信公众号参数
          this.wxConfig(response.data.params);
          //上传
          this.wxUoloadImage(that);
        } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误' + response.data.msg);
        }
      });
    },
    getCustomers: function() {
      let that = this;
          this.axios({
              method: 'post',
              url: '/sales/Customer!getCustomers.action',
              //params: {functiontype: 17}
              params: {functiontype: 13}
          }).then(response => {
              if (response.data.msg == "success") {
                  this.customers = response.data.customers;
                  //从订单列表返回执行
                  if (this.customerid != '') {
                    this.customer = this.customers.filter(function (item) {
                      return item.guid == that.customerid;
                    })[0] || '';
                  }
              } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
                  this.toastText('获取客户数据失败');
              }
          });
      },

    switchChecked: function (status, elem) {
      if (status) {
        for (var i=0; i< elem.length; i++) {
          if (elem.eq(i).is(':checked')) {
            elem.eq(i).click();
          }
        }
        this.switchBtnStyle(false);
      } else {
        for (var i=0; i< elem.length; i++) {
          if (!elem.eq(i).is(':checked')) {
            elem.eq(i).click();
          }
        }
        this.switchBtnStyle(true);
      }
    },
    switchBtnStyle: function (status){
      if (status) {
        $('#allSec').find('i').removeClass("weui-icon-circle");
        $('#allSec').find('i').addClass("weui-icon-success");
        this.selected = false;
      } else {
        $('#allSec').find('i').removeClass("weui-icon-success");
        $('#allSec').find('i').addClass("weui-icon-circle");
        this.selected = true;
      }
    },
    addOrder: function() {
      if (this.customerid != '') {
        this.$router.push({name: 'PaybackOrdersList', query: {customerid: this.customerid, customername: this.customer.name, currency: this.customer.currency}});
      } else {
        this.toastText('请选择客户');
      }
    },
    getFinalAmount: function() {
      let totalAmoumt = 0;
      let totalCarnum = 0;
      let orders = this.orders;
      this.totalGuids = "";

      for (var i=0; i<orders.length; i++) {
        totalAmoumt += orders[i].amount;
        this.totalGuids = this.totalGuids + orders[i].orderid + ',';
        totalCarnum += 1;
      }


      $('#amount i').text(this.toDecimal2NoZero(totalAmoumt));
      this.totalAmoumt = this.toDecimal2NoZero(totalAmoumt);
      $('#carnum i').text(totalCarnum);
      this.totalGuids = this.totalGuids.substr(0,this.totalGuids.length-1);
    },
    postForm: function () {
      let that = this;

      if (this.customerid == '') {
        this.toastText('请选择客户！');
        return false;
      } else if (this.totalAmoumt <= 0) {
        this.toastText('回款金额有误！');
        return false;
      } else if (this.customer.prebalance < this.totalAmoumt) {
        this.toastText('客户预收款余额不满足要求！');
        return false;
      }
      //防止重复提交
      $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

      let postData = {};
      postData = this.serialize2Obj($("#formid").serializeArray());
      postData.imgids = this.images.serverId.join(',');
      postData.ids = this.totalGuids;
      postData.prepaid = this.totalAmoumt;
      //postData.opttype = 17;
      this.axios({
        method: 'post',
        url: '/pay/Paybackinfo!paybackSFWx.action',
        params: postData
      }).then(response => {
        //恢复提交按钮可点击
        $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
        if (response.data.code == 1) {
          this.toastSuccess('提交成功!');
          this.$router.push({name: 'Paybacklist'});
        } else if (response.data.code == 0) {
            this.toastText(response.data.msg);
        }else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误');
        }
      }).catch(function (error) {
        //恢复提交按钮可点击
        $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
        that.toastError('系统错误');
      });

    }
  }
}
</script>
